<script setup>
import List from '../components/List.vue'
import ClusterNamespaceSelector from '../components/ClusterNamespaceSelector.vue'
import { getStatefulSetListHandler as getListHandler, deleteStatefulSetHandler as deleteHandler, updateStatefulSetHandler } from '../../api/statefulset.js'
import { ElMessage, ElMessageBox  } from 'element-plus'
import { ref, reactive, computed } from 'vue'
// import CodeMirror from '../components/CodeMirror.vue'
import DialogYaml from '../components/DialogYaml.vue' // codeMirror 从DialogYaml组件引用
import { toRefs } from 'vue'
import { obj2Yaml } from '../../utils/utils'
import { useRouter } from 'vue-router'
import GenericOptions from '../components/GenericOptions.vue'


const router = useRouter()
const data = reactive({
  items: [],
  clusterId: "",
  namespace: "",
  deleteItem: "",
  yamlContent: ""
})

// 定义查询pod列表函数
const getList = () => {
  getListHandler(data.clusterId,data.namespace).then(
    (res) => {
      data.items = res.data.data.items
      console.log("statefulset列表",data.items)
    }
  )
}

// 回调函数传给ClusterNamespaceSelector组件
const rollback = (clusterId,namespace) => {
  data.clusterId = clusterId
  data.namespace = namespace
  getList()
}

const filterTableData = computed(() =>
  data.items.filter(
    (item) =>
      !search.value ||
      item.metadata.name.toLowerCase().includes(search.value.toLowerCase())
  )
)
const search = ref('')

// 判断pod重启次数和状态
const getPodRestartCount = computed(() => (row) => {
  console.log("row",row)
  let restartCount = 0
  let readyCount = 0
  row.status.containerStatuses.forEach(item => {
    restartCount += item.restartCount
    if (item.ready) { // 容器就绪
      readyCount += 1
    }
  })
  // 获取当前pod有多少个container
  const containerTotal = row.status.containerStatuses.length
  const readStatus = `${readyCount}/${containerTotal}`
  return [restartCount,readStatus]
})

const showDetail =ref(false)
const detail = (row) => {
  const item = JSON.parse(JSON.stringify(row))
  delete item.metadata.managedFields // 删除maangeFields字段
  // delete metadata.status // 删除status字段
  const itemtemp = {// yaml补上apiVersion字段
    "apiVersion": "apps/v1",
    "kind": "StatefulSet",
    "metadata": item.metadata,
    "spec": item.spec
  }
  const yamlData = obj2Yaml(itemtemp)// 当前数据转成yaml
  data.yamlContent = yamlData
  showDetail.value = true
}
const { yamlContent, clusterId } = toRefs(data)

const changeReplicas = (newValue, oldValue, row, resourceType) => {
  console.log(`新值：${newValue}, 旧值：${oldValue}, 当前资源副本数：${row.spec.replicas}, 资源类型：${resourceType}`)
  ElMessageBox.confirm(
    `确定要更改${resourceType}: ${row.metadata.name}的副本数为${newValue}吗？`,
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => { //点击创建
    const postData = {
      clusterId: data.clusterId,
      namespace: data.namespace,
      item: row
    }
    updateStatefulSetHandler(postData).then((res) => {
      ElMessage.success(res.data.message)
    }).catch((res) => {
      row.spec.replicas = oldValue
      ElMessage.warning(res.data.message)
    })
  }).catch(() => { //点击取消
    row.spec.replicas = oldValue
  })
}
</script>

<template>
  <List title="StatefulSet列表">
    <template #header-options>
      <ClusterNamespaceSelector @namespaceChangedRollback="rollback">
      </ClusterNamespaceSelector>
      <el-input v-model="search" size="small" placeholder="搜索" style="width: 140px; margin-left: 10px; height: 32px;"/>
    </template>
    <template #main>
      <el-table
      border
      height="480"
      :data="filterTableData"
      style="width: 100%"
      :default-sort="{prop:'metadata.creationTimestamp',order:'descending'}"
      >
        <el-table-column fixed prop="" align="center" label="名称">
          <template #default="scope">
            <el-button link type="primary"  @click="detail(scope.row)">{{ scope.row.metadata.name }}</el-button>
          </template>
        </el-table-column>

        <el-table-column prop="metadata.creationTimestamp" align="center" label="创建时间" width="180" sortable/>

        <el-table-column prop="" align="center" label="副本数" width="180" @change="">
          <template #default="scope">
            <el-input-number v-model="scope.row.spec.replicas" :min="0" :max="100" placeholder="请输入副本数" :controls="false"
            @change="(currentValue, oldValue) => changeReplicas(currentValue, oldValue, scope.row, 'statefulset')"/>
          </template>
        </el-table-column>

        <el-table-column prop="" align="center" label="状态" width="120">
          <template #default="scope">
            <span title="成功启动的副本/期望副本" v-if="scope.row.spec.replicas != 0" style="color: green;">
              {{ scope.row.status.readyReplicas }}/{{ scope.row.status.replicas }}
            </span>
            <span v-else  style="color: red;">{{ scope.row.status.phase }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="spec.serviceName" label="无头服务" align="center">
        </el-table-column>
        <el-table-column prop="metadata.namespace" align="center" label="命名空间" width="120"/>
        <el-table-column fixed="right" align="center" label="操作" width="320">
          <template #default="scope">
            <GenericOptions
              v-on:delete-rollback="getList"
              :disabled="scope.row.metadata.deletionTimestamp != undefined"
              :show-schedule-options="true"
              resource-type="StatefulSet"
              :name="scope.row.metadata.name"
              :namespace="scope.row.metadata.namespace"
              :cluster-id="clusterId"
              :item="scope.row"
            ></GenericOptions>
          </template>
        </el-table-column>
      </el-table>
    </template>
  </List>
  <DialogYaml
  :cluster-id="data.clusterId"
  :namespace="data.namespace"
  :yaml-content="yamlContent"
  :show-dialog="showDetail"
  @close-dialog-handler="(val) => {showDetail = val }"
  >
  </DialogYaml>
</template>

<style scoped>
</style>
